# !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:张广勤
@Web site: https://www.tunan.wang
@Github:www.github.com
 
@File:chat_input1_0.py
@Time:2024/7/1 19:20

@Motto:不积跬步无以至千里，不积小流无以成江海！
"""
import streamlit as st

from Spark_chat import SparkApi
import time

# 以下密钥信息从控制台获取   https://console.xfyun.cn/services/bm35
appid = "7c7d68a2"  # 填写控制台中获取的 APPID 信息
api_secret = "NzUxODZkNzgwMjE2M2Y5YWQwYjhhOWEw"  # 填写控制台中获取的 APISecret 信息
api_key = "3531a2e16bd85483cead10922e2c857d"  # 填写控制台中获取的 APIKey 信息

domain = "generalv3.5"  # Max版本

Spark_url = "wss://spark-api.xf-yun.com/v3.5/chat"  # Max服务地址

# 初始上下文内容，当前可传system、user、assistant 等角色
text = [
    # {"role": "user", "content": "你会做什么"}  # 最新的一条问题，如无需上下文，可只传最新一条问题
]


# def getText(role, content):
#     jsoncon = {}
#     jsoncon["role"] = role
#     jsoncon["content"] = content
#     text.append(jsoncon)
#     return text

def getText(role, content, text):
    jsoncon = {}
    jsoncon["role"] = role
    jsoncon["content"] = content
    text.append(jsoncon)
    return text


def getlength(text):
    length = 0
    for content in text:
        temp = content["content"]
        leng = len(temp)
        length += leng
    return length


# def checklen(text):
#     while (getlength(text) > 8000):
#         del text[0]
#     return text

def checklen(messages):
    while sum(len(msg["content"]) for msg in messages) > 8000:
        del messages[0]
    return messages

def stream_data(text):
    words = text.split("，")
    for i, word in enumerate(words[:-1]):
        yield word + "，"
        time.sleep(0.1)
    if words:
        yield words[-1]  # 输出最后一个词，不带逗号
    # for word in text.split("，"):
    #     yield word + "，"
    #     time.sleep(0.1)

st.title("简单聊天界面")

if "messages" not in st.session_state:
    st.session_state.messages = []  # 初始化消息列表

# 显示之前的聊天消息
for message in st.session_state.messages:
    with st.chat_message(message["role"]):
        st.markdown(message["content"])

# 获取用户输入的新消息
prompt = st.chat_input("请输入消息")

if prompt:
    # 将用户输入的消息添加到消息列表中
    st.session_state.messages.append({"role": "user", "content": prompt})
    with st.chat_message("user"):
        st.markdown(prompt)  # 在聊天窗口中显示用户的消息

    # 这里可以添加对用户输入的处理逻辑，例如发送给后端或进行其他操作
    question = checklen(st.session_state.messages)
    # question = checklen(getText("user", prompt, st.session_state.messages))
    # question = checklen(getText("user", prompt))
    SparkApi.answer = ""
    SparkApi.main(appid, api_key, api_secret, Spark_url, domain, question)
    # print("星火:", end="")
    # question = checklen(getText("user", prompt))
    # SparkApi.answer = ""
    # print("星火:", end="")
    # SparkApi.main(appid, api_key, api_secret, Spark_url, domain, question)
    # # print(SparkApi.answer)
    # getText("assistant", SparkApi.answer)
    # 为了简单起见，这里直接显示一个回复消息
    response = f"{SparkApi.answer}"
    with st.chat_message("assistant"):
        st.write_stream(stream_data(response))
        # st.markdown(SparkApi.answer)
        # st.markdown(response)  # 在聊天窗口中显示回复消息
    st.session_state.messages.append({"role": "assistant", "content": response})
    # st.session_state.messages.append({"role": "assistant", "content": response})
